package yygh.cmn.Service.imp;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import yygh.hospital.model.cmn.Dict;
import yygh.hospital.vo.cmn.DictEeVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import yygh.cmn.Service.DictService;
import yygh.cmn.listener.DictVoListener;
import yygh.cmn.mapper.DictMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImp extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    DictMapper dictMapper;


    //根据id查询是否存在子节点（查找parent_id字段和id字段相同的数据）
    // @Cacheable(value = "dict",keyGenerator = "keyGenerator")实现了基于redis的数据的缓存
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id){
        //复杂查询QueryWrapper对象
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dicts = dictMapper.selectList(wrapper);
        //将dicts列表的所有是否包含子节点属性设置为true；
        for (Dict dict:dicts){
            Long dictId = dict.getId();
            boolean ischild = this.ischild(dictId);
            dict.setHasChildren(ischild);
        }
        return dicts;
    }


    //判断指定id指是否存在子节点（查找parent_id字段和id字段相同的数据的数量）
    private boolean ischild(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = dictMapper.selectCount(wrapper);
        //若count大于0，说明存在子节点
        return count>0;
    }

    //读取数据库的内容，导出到excel表中
    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //读取数据库的信息
        List<Dict> list = dictMapper.selectList(null);
        /**
         *  读取出来的list为Dict类，我们要写入的DictVo类的集合数据，因此需要将list集合取出来，然后根据DictVo的类信息复制给DictVo
         *
         */
        List<DictEeVo> dictEeVoList =new ArrayList<>();
        for (Dict dict:list){
            //创建一个DictVo对象
            DictEeVo  dictVo=new DictEeVo();
            BeanUtils.copyProperties(dict,dictVo);
            dictEeVoList.add(dictVo);
        }
        //调用EasyExcel相应的方法进行导出
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //读取excel中的数据字典文件，并存入到数据库中
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),new DictVoListener(dictMapper)).sheet("dict").doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //根据dictCode和value查询相应的字段
    @Override
    public String getDictName(String dictCode, String value) {
        //判断dictCode是否为空
        if (StringUtils.isEmpty(dictCode)){
            //如果dictCode为空，只需要根据value查询即可
            //查询省市区
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = dictMapper.selectOne(wrapper);
            return dict.getName();
        }else {
            //如果dictCode不为空，查询医院等级
            //step1:首先根据dictCode查询对应的上一级
            QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("dict_code", dictCode);
            Dict Parentdict = dictMapper.selectOne(queryWrapper);
            Long id = Parentdict.getId();
            //查找所有parent_id与id相同的字段
            QueryWrapper<Dict> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("parent_id",id).eq("value",value);
            Dict Finaldict = dictMapper.selectOne(queryWrapper1);
            return Finaldict.getName();
        }
    }

    //根据dictCode查询子节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //首先根据传入的dictCode查询id值，
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        Dict dict  = dictMapper.selectOne(queryWrapper);
        //查询子节点（然后根据id值查询所有parent_id与id值相同的字段）
        List<Dict> dictList = this.findChildData(dict.getId());
        return  dictList;
    }
}
